<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['vcenter','rowbottom',i1===0?'rowtop':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="4">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row
                  :class="['vcenter',(i2===0)?'':'rowtop']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="editRight(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 权限编辑对话框 -->
    <el-dialog title="分配权限" :visible.sync="editRightVisible" width="30%" @close="closeEditRight">
      <el-tree
        ref="refRightsTree"
        show-checkbox
        default-expand-all
        node-key="id"
        :data="rightsList"
        :props="rightsTreeProps"
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [], // 所有角色数据
      rightsList: [], // 所有权限数据
      rightsTreeProps: { children: 'children', label: 'authName' }, // 权限数格式
      editRoleId: '',
      defKeys: [], // 默认选中的节点ID
      editRightVisible: false // 是否显示分配权限对话框
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获得角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 根据ID删除对应的权限
    async removeRightById(role, rightsID) {
      const confirmRes = await this.$confirm('确实要删除该权限吗？', '请确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmRes !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        'roles/' + role.id + '/rights/' + rightsID
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      role.children = res.data
    },
    // 编辑权限
    async editRight(role) {
      this.editRoleId = role.id
      // 获取权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      // 获得
      this.getLeafKeys(role, this.defKeys)
      // 打开对话框
      this.editRightVisible = true
    },
    // 通过递归，获得角色的所有三级权限的id，保存到this.defKeys
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 关闭权限编辑
    closeEditRight() {
      this.defKeys = []
    },
    // 保存角色权限
    async saveRoleRights() {
      const keys = [
        ...this.$refs.refRightsTree.getCheckedKeys(),
        ...this.$refs.refRightsTree.getHalfCheckedKeys()
      ]
      const { data: res } = await this.$http.post(
        'roles/' + this.editRoleId + '/rights',
        { rids: keys.join(',') }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.editRightVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.rowtop {
  border-top: 1px solid #eee;
}
.rowbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 5px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>